<template>
  <div class="container h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      :showMore="true"
      showTopTitle
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>厂站操作票 (样票)</template
      >
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!-- <label>参数组名称</label> -->
          <el-input
            type="text"
            maxlength="64"
            show-word-limit
            v-model.trim="titleName"
            @blur="loseFocus"
            placeholder="请输入标题"
            clearable
            ref="mark"
            ><template slot="prepend" style="color: red"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse value="basic" style="padding-right: 10px">
        <el-collapse-item name="basic">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <editForm
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="formData"
          >
          </editForm>
          <stepList
            :formListData="stepListData"
            ref="stepList"
            :isReadonly="isReadonly"
            :status="status"
            :ticketId="ticketId"
          ></stepList>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
  </div>
</template>
<script>
import stepList from "../operationTicketProcessing/stepList";
import {
  operationTicketDetail,
  sampleTicketDetail,
  saveSampleTicket,
  deleteSampleTicket,
} from "@/api/twoTicketManagement/operationTicket.js";
export default {
  components: { stepList },
  data() {
    return {
      title: "", //一级标题
      titleName: "", //二级标题
      pageType: "",
      ticketId: "",
      stepConfig: {},
      status: 0,
      //打印操作票的地址
      printSrc: "",
      formData: null,
      stepListData: [{ rowNum: "1", item: "", marks: null, remarks: null }], //操作步骤数据
      isReadonly: false, //操作步骤设置只读
      showInput: false,
      moreBtnArr: [
        {
          text: "操作记录",
          // icon: "el-icon-printer",
          methods: async () => {},
        },
      ],
      //基本信息配置
      basicConfig: {
        labelWidth: "140px",
        itemArr: [
          {
            label: "操作票类型：",
            prop: "group",
            type: "select",
            required: true,
            disabled: true,
            span: 8,
            selectOption: this.$store.getters["dirtData"](
              "ticket_operation_group"
            ),
          },
          {
            label: "操作票子类：",
            prop: "type",
            type: "select",
            required: false,
            span: 8,
            selectOption: this.$store.getters["dirtData"](
              "ticket_operation_type"
            ),
          },
          {
            label: "操作任务：",
            prop: "context",
            type: "textarea",
            maxlength: "1000",
            rows: 4,
            required: false,
            span: 24,
          },
        ],
      },
      filesList: [],
    };
  },
  created() {
    this.init();
  },
  methods: {
    /**
     * 初始化页面数据
     * */
    async init() {
      this.pageType = this.$route.query.pageType;
      this.pageType === "details" && this.getDetails("details");
      this.pageType === "addImport" && this.getDetails("addImport");
      if (this.pageType === "add") {
        this.showInput = true;
        this.$nextTick(() => {
          this.$refs.basicForm.setFormItem("group", "factory");
        });
      }
    },
    /**
     * 获取当前数据详情
     * */
    async getDetails(type) {
      this.ticketId = this.$route.query.id;
      let res = null;
      if (type === "details") {
        res = await sampleTicketDetail(this.ticketId);
      } else if (type === "addImport") {
        res = await operationTicketDetail({ id: this.ticketId });
      } else {
        return;
      }
      if (res.code === 200) {
        this.formData = res.data;
        this.stepListData = res.data.stepdet.map((obj) => {
          return {
            rowNum: obj.sort,
            item: obj.item,
            marks: obj.marks,
            remarks: obj.remarks,
          };
        });
        this.titleName = res.data.title;
      }
    },

    /**
     * 保存按键
     * */
    async save() {
      if(!this.titleName){
       this.$message.warning("标题不能为空");
        return
      }
      const data = await this.$refs.basicForm.getFormData();
      //由历史导入的数据需清掉id
      this.pageType === "addImport" && delete data.id;
      data.title = this.titleName;
      //校验操作步骤至少要有一行数据
      const stepdet = this.$refs.stepList.listConfig.listData;
      if (stepdet.length == 0) {
        this.$message.error("请填写操作项目！");
        return false;
      }
      //校验操作步骤必填信息
      let hasEmpty = false;
      stepdet.filter((step) => {
        if (hasEmpty) return;
        if (step.item.trim() === "") {
          this.$message.error("第" + step.rowNum + "行操作项目不能为空！");
          hasEmpty = true;
          return;
        }
      });
      if (hasEmpty) return;
      data.stepdet = stepdet.map((obj) => {
        const { rowNum, item, marks, remarks } = obj;
        return { sort: rowNum, item, marks, remarks };
      });

      const res = await saveSampleTicket(data);
      res.code === 200 &&
        this.$message({
          type: "success",
          message: "保存成功!",
        });
      res.code === 200 &&
        this.$router.replace({
          name: "substationSimpleDetails",
          query: {
            random: Math.random().toFixed(4) * 10000, //解决路由重复问题
            pageType: "details",
            id: res.data,
          },
        });
      this.updateListData();
    },
    /**
     * 删除
     * */
    async deleteBtn() {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let deleteRes = await deleteSampleTicket(this.ticketId);
          if (deleteRes.code === 200) {
            this.$message.success("删除成功");
            this.updateListData();
            setTimeout(() => {
              window.close();
            }, 1000);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
    /**
     * 编辑标题
     * */
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    /**
     * 标题输入框失去焦点
     * */
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.$message.warning("标题不能为空");
      }
    },
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-position",
          methods: () => {
            this.curClickBtn = "save";
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete",
          methods: () => {
            this.curClickBtn = "del";
            this.deleteBtn("删除");
          },
        },
      ];
      return arr;
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  padding: 0px 100px;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>